import {Component, ViewChild} from '@angular/core';
import {Events, IonicPage, ModalController, Navbar, NavController, NavParams} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {Util} from "@providers/util";
import {CustomerProvider} from "@providers/interface/customer";
import {DialogProvider} from "@providers/dialog";

/**
 * Generated class for the CustomerAppointmentPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-customer-appointment',
  templateUrl: 'customer-appointment.html',
})
export class CustomerAppointmentPage {

  @ViewChild(Navbar) navbar: Navbar;

  theadd: any[] = [];//默认地址
  dzbor: boolean = false;
  ct: any = {
    "ztime": {
      "thedate": new Date(),
      "bor": true
    },
    "dtime": {
      time: "9:00-11:45", "bor": true, "FWSJD": "0"
    }
  }; //预约时间显示

  timelist: any[] = [];//未来十天列表；
  amap: any[] = [{time: "9:00-11:45", "bor": true, "FWSJD": "0"}, {time: "13:00-18:00", "bor": false, "FWSJD": "1"},
    {time: "9:00-18:00", "bor": false, "FWSJD": "2"}];//选择上下午
  serviceType: any = {value: '请选择服务类型'};//上个传参

  userinfo: any = this.storage.read("userInfo");
  tanbor: boolean = true;//控制弹出层

  serviceTypes: any[] = [];//服务类型列表
  categorys: any[] = [];//分类列表
  brands: any[] = [];//品牌列表
  troubles: any[] = [];//故障类型列表

  category: any = {VALUE: '请选择品类'};//选中的分类
  brand: any = {VALUE: '请先选择品类'};//选中的品牌
  trouble: any = {VALUE: '请先选择品类'};//选中的故障类型

  gzms: string = '';//故障描述

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private modalCtrl: ModalController,
              private storage: StorageProvider,
              private dialog: DialogProvider,
              private customer: CustomerProvider,
              private events: Events,) {
  }

  ionViewDidLoad() {
    let date = new Date();
    date.setTime(new Date().getTime() + (24 * 60 * 60 * 1000));
    this.ct.ztime.thedate = date;
    console.log('ionViewDidLoad CustomerAppointmentPage');
  }

  ionViewWillEnter() {
    Util.replaceBackButtonEvent(this.navbar, this.navCtrl, this.events);
    this.initData();
  }

  initData() {
    this.getFWLX();
    this.getGZLX();
    this.getPPXX();
    this.initDate();
    this.getDefaultAddress();
  }

  initDate() {
    this.timelist = [];
    for (let i = 1; i < 10; i++) {
      let day3 = new Date();
      let time = {};
      day3.setTime(day3.getTime() + i * 24 * 60 * 60 * 1000);
      time["thedate"] = day3;
      if (i == 1) {
        time["bor"] = true;
      } else {
        time["bor"] = false;
      }
      this.timelist.push(time)
    }
  }

  getDefaultAddress() {
    this.customer.getCustomerInfo({
      "PARTYID": this.userinfo.PARTYID,
      "MRDZ": "1"
    }).then((message) => {
      this.theadd = message['data'];
      console.log(this.theadd);
      this.dzbor = true;
    }).catch(() => {
    });
  }

  /**
   * 获取故障类型
   */
  getGZLX() {
    this.customer.getGZLX({}).then(message => {
      this.troubles = message.data;
    }).catch((error) => {
      this.dialog.showAlert("请检查网络！" + JSON.stringify(error));
    });
  }

  /**
   * 获取品牌品类
   */
  getPPXX() {
    this.customer.getPPXX({}).then(message => {
      this.categorys = message.data;
    }).catch((error) => {
      this.dialog.showAlert("请检查网络！" + JSON.stringify(error));
    });
  }

  /**
   * 获取服务类型
   */
  getFWLX() {
    this.customer.getFWLX({'LX': '-1'})
      .then((message) => {
        this.serviceTypes = message.data;
      }).catch((error) => {
      this.dialog.showAlert("请检查网络！" + JSON.stringify(error));
    });
  }

  /**
   * 选择预约日期
   * @param d
   */
  choosetime(d: any) {
    this.timelist.forEach((v, i) => {
      v.bor = false;
    });
    d.bor = true;
    this.ct["ztime"] = d;
  }

  /**
   * 选择预约日期中的时间段
   * @param a
   */
  chooseap(a: any) {
    this.amap.forEach((v) => {
      v.bor = false;
    });
    a.bor = true;
    this.ct["dtime"] = a;

    this.tanbor = !this.tanbor;
  }

  /**
   * 弹出日期选择框
   */
  tanchu() {
    this.tanbor = !this.tanbor;
  }

  /**
   * 跳转页面，获取返回数据
   * @param page 跳转的目标页面
   */
  push(page: string) {
    let modal = this.modalCtrl.create(page);
    modal.onDidDismiss((da) => {
      if (da) {
        let a: any[] = [];
        a.push(da);
        this.theadd = a;
      }
    });
    modal.present();
  }

  /**
   * 选择分类点击事件
   */
  chooseCategory() {
    let type = [];
    this.categorys.forEach(value => {
      type.push({
        text: value.VALUE,
        handler: () => {
          this.brands = value.SPPP;
          this.troubles = value.GZMC;
          this.category = value;
          this.brand = {VALUE: '请选择品牌'};//选中的品牌
          this.trouble = {VALUE: '请选择故障类型'};//选中的故障类型
        }
      });
    });
    this.dialog.showActionSheet(type, '请选择商品分类');
  }

  /**
   * 选择品牌点击事件
   */
  chooseBrand() {
    if (!this.category.KEY) {
      return;
    }
    let type = [];
    this.brands.forEach(value => {
      type.push({
        text: value.VALUE,
        handler: () => {
          this.brand = value;
        }
      });
    });
    this.dialog.showActionSheet(type, '请选择商品品牌');
  }

  /**
   * 选择故障类型点击事件
   */
  chooseTrouble() {
    if (!this.category.KEY) {
      return;
    }
    let type = [];
    this.troubles.forEach(value => {
      type.push({
        text: value.VALUE,
        handler: () => {
          this.trouble = value;
        }
      });
    });
    this.dialog.showActionSheet(type, '请选择故障类型');
  }

  /**
   * 服务类型点击事件
   */
  chooseServiceType() {
    let type = [];
    this.serviceTypes.forEach(value => {
      type.push({
        text: value.VALUE,
        handler: () => {
          this.serviceType = {
            "key": value.KEY,
            "value": value.VALUE
          };
        }
      })
    });
    console.info(type);
    this.dialog.showActionSheet(type, '请选择服务类型');
  }


  checkData(page: string) {
    if (!this.serviceType.key) {
      this.dialog.showAlert('请选择服务类型！');
      return;
    }
    if (this.theadd.length == 0) {
      this.dialog.showAlert('请选择地址！');
      return;
    }
    if (!this.category.KEY) {
      this.dialog.showAlert('请选择商品分类！');
      return;
    }
    if (!this.brand.KEY) {
      this.dialog.showAlert('请选择商品品牌！');
      return;
    }
    if (!this.trouble.KEY && this.serviceType.key == '3') {
      this.dialog.showAlert('请选择故障类型！');
      return;
    }
    this.submit(page)
  }

  submit(page: string) {

    this.dialog.showConfirm(() => {
      let spmc: string = this.serviceType.value + '(系统)';
      let cdcs = {
        "LXDH": this.theadd[0].LXDH,
        "partyId": this.userinfo.PARTYID,
        "DQXX01": this.theadd[0].DQXX01,
        "KHXM": this.theadd[0].KHXM,
        "XXDZ": this.theadd[0].XXDZ,
        "STUATS": this.theadd[0].STUATS,
        "FWLX": this.serviceType,
        "SPLB": [                //   --商品列表
          {
            "PPBM": this.brand.KEY,
            "PPMC": this.brand.VALUE,
            "SPMC": spmc,
            "SL": "1",
            //         "FLMC": "1.5匹以下",
            "FLMC": this.category.VALUE,
            //         "SPBM": "00000009",
            "FLBM": this.category.KEY,
            "GG": "台"
          }
        ],
        "FWSJ": Util.getymd(this.ct.ztime.thedate),
        "FWSJD": this.ct.dtime.FWSJD,              // --服务时间段（上午，下午，全天）
        "ZDRMC": this.userinfo.USERNAME,
        "KHJDBJ": 1,
        "source": "KHJD",
      };
      if (this.serviceType.key == '3') {
        cdcs['GZLX'] = this.trouble;
        cdcs['FWBZ'] = this.gzms;
      }
      // console.log(JSON.stringify(cdcs));
      this.customer.addAppointment(cdcs).then(message => {
        if(!message.data.street){
          message.data['street']=message.data.district;
        }
        this.customer.queryAppointment({"SYSJ": message.data.street}).then((message2) => {
          message.data['alldz'] = message2.data;
          this.navCtrl.push(page, message.data);
        }).catch(() => {
        });
      }).catch(() => {
      });
    }, "是否确认提交?")
  }

}
